<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>计算器</title>
  </head>
  <body>
    <div>
      <input type="text" size="5" id="num1" value="" />
      <select id="operator">
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="*">*</option>
        <option value="/">/</option>
        <option value="%">%</option>
      </select>
      <input type="text" size="5" id="num2" value="" />
      <input type="button" id="btn" value="计算" />
    </div>
    <p id="res">请输入运算值</p>

    <script>
      // 获取按钮注册事件
      document.getElementById("btn").onclick = function () {
        var num1 = document.getElementById("num1").value;
        var num2 = document.getElementById("num2").value;
        var operators = document.getElementById("operator").value;
        var flag = true; // 作为标记

        var result = "Error：";
        if (num1 == "") {
          result += "第一个运算符为空#";
          flag = false;
        }else{
          num1 = parseFloat(num1)
          if(isNaN(num1)){
            result+="第一个运算数不是一个有效的数字#";
            flag=false;
            console.log(num1)
          }
        }
        if (num2 === "") {
          result += "第二个运算符为空#";
          flag = false;
        }else{
          if(isNaN(num2)){
          num2 = parseFloat(num2)
            result+="第二个运算数不是一个有效的数字#";
            flag=false;
          }
        }

        num1=parseFloat(num1)
        num2=parseFloat(num2)
        if (flag) {
          switch (operators) {
            case "+":
              result =
                "运算结果: " + num1 + " + " + num2 + " = " + (num1 + num2);
              break;
            case "-":
              result =
                "运算结果: " + num1 + " - " + num2 + " = " + (num1 - num2);
              break;
            case "*":
              result = "运算结果: " + num1 + " * " + num2 + " = " + num1 * num2;
              break;
            case "/":
              if (num2 == 0) {
                result = "除数不能为0";
              } else {
                result =
                  "运算结果: " + num1 + " / " + num2 + " = " + num1 / num2;
              }
              break;
            case "%":
              if (num2 == 0) {
                result = "除数不能为0";
              } else {
                result =
                  "运算结果: " + num1 + " % " + num2 + " = " + (num1 % num2);
              }
              break;
          }
        }
          document.getElementById("res").innerText = result;
        };
    </script>
  </body>
</html>
